<?php

namespace App\Jobs;

use App\Http\Controllers\Api\Repositories\PostsRepositores;
use App\Models\Posts\WxPost;
use App\Wen\Utils\UserUtils;
use App\Wen\Utils\Utils;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Redis;

class ImitatePostlikesStepJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    public $tries = 1;
    protected $post_id = 0;
    protected $need_like = 0;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($post_id, $need_like)
    {
        //
        $this->post_id = $post_id;
        $this->need_like = $need_like;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        //
        global $__MINI_GLOBAL_PAYCODE_9__;
        if(!$__MINI_GLOBAL_PAYCODE_9__){
            return;
        }
        if( $this->need_like <= 0 ){
            return;
        }

        global $__MINI_GLOBAL_REQUEST_ENV__;
        $__MINI_GLOBAL_REQUEST_ENV__ = 'api';

        if(WxPost::where('id', $this->post_id)->where('is_examine', 1)->where('posts_state', 0)->exists()){
            $uid = UserUtils::get_a_random_robot_uid();
            if($uid){
                global $__MINI_GLOBAL_IS_ADMIN_SUPER__;
                $post_user_id = WxPost::where('id', $this->post_id)->value('user_id');
                if($post_user_id > 0 && in_array($post_user_id, explode(',', env('APP_SUPER_ADMIN_USER_ID', '')))){
                    $__MINI_GLOBAL_IS_ADMIN_SUPER__ = true;
                }
                PostsRepositores::addLike($uid, $this->post_id);
                $__MINI_GLOBAL_IS_ADMIN_SUPER__ = false;

                $like_count = PostsRepositores::likeCont($this->post_id);
                $weight = WxPost::where('id', $this->post_id)->value('weight');
                $weight += ( Utils::getDecayCoefficient($like_count, 10) * 400);
                if($weight > time()){
                    $weight = time();
                }
                $posts_id = $this->post_id;
                WxPost::withoutSyncingToSearch(function () use ($posts_id, $weight) {
                    WxPost::where('id', $posts_id)->update(['weight' => timetostr($weight)]);
                });
                Redis::sadd('realtime:post:set', $this->post_id);

                ImitatePostlikesStepJob::dispatch($this->post_id, ($this->need_like - 1))->delay(now()->addMinutes(mini_rand(6, 30)));
            }
        }

    }
}
